import {
  reqGetCode,
  reqUserRegister,
  reqUserLogin,
  reqUserInfo,
  reqLogout
} from "@/api"
import {setToken,getToken,removeToken} from "@/utils/token.js"
const state = {
  code: "",
  token:getToken(),
  userInfo:{},
  
}

const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state,token){
    state.token = token
  },
  GETUSERINFO(state,userInfo){
    state.userInfo=userInfo
  },
  //清楚本地数据
  CLEAR(state){
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}

const actions = {
  //获取验证码
  async getCode({commit}, phone) {
    let res = await reqGetCode(phone)
    if (res.code == 200) {
      commit("GETCODE", res.data)
    }else{
      alert("cuosjhio")
    }
  },

  //用户注册 
 async userRegister({commit},user){
    let res =  await  reqUserRegister(user)
 
      if(res.code==200){
        
      return "ok"
    }else{
      return Promise.reject(new Error(res.message))
    }
  },

    //登入
async  userLogin({commit},data) {
  let res = await reqUserLogin(data)
  if(res.code==200){
    commit("USERLOGIN",res.data.token)
    setToken(res.data.token)
    return "ok"
    
  }else 
  {
    return Promise.reject(new Error(res.message))
  }
}
,

//获取用户信息
async getUserInfo({commit}){
  let res  = await   reqUserInfo();
  if(res.code == 200){
    commit("GETUSERINFO",res.data)
    return 'ok'
  }else{
    return Promise.reject(new Error(res.message))
  }
},
//退出登录
async userLogout({commit}){
   let  res = await reqLogout()
    if(res.code==200){
      commit('CLEAR')
      return "ok"
    }else{
      return Promise.reject(new Error(res.message))
    }

}
}

const getters = {


}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
